package com.example.basic1.controller;

import com.example.basic1.common.Result;
import com.example.basic1.entity.User;
import com.example.basic1.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.*;
import com.example.basic1.common.Page;

import java.util.List;
import java.util.Map;

@CrossOrigin
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @PostMapping("/add")
    public Result add(@RequestBody User user){
        try {
            userService.insertUser(user);
        }catch (Exception e) {
            if (e instanceof DuplicateKeyException){
                return Result.error("数据库插入错误");
            }else{
                return Result.error("系统错误");
            }
        }

        return Result.success();
    }

    @PutMapping("/update")
    public Result updateUser(@RequestBody User user){
        userService.updateUser(user);

        return Result.success();
    }

    @DeleteMapping("/delete/{id}")
    public Result delete(@PathVariable Integer id){
        userService.deleteUser(id);

        return Result.success();
    }

    @DeleteMapping("/delete/batch")
    public Result deleteMany(@RequestBody List<Integer> ids){
        userService.deletebatchUser(ids);

        return Result.success();
    }

    @GetMapping("/selectAll")
    public Result selectAll(){
        List<User> users = userService.selectAll();

        return Result.success(users);
    }

    @GetMapping("/selectById/{id}")
    public Result selectById(@PathVariable Integer id){
        User user = userService.selectById(id);

        return Result.success(user);
    }

    @GetMapping("/selectByName/{name}")
    public Result selectByName(@PathVariable String name){
        List<User> users = userService.selectByName(name);

        return Result.success(users);
    }

    @GetMapping("/selectByMore")
    public Result selectByMore(@RequestParam String username, @RequestParam String name){
        List<User> users = userService.selectByMore(username, name);

        return Result.success(users);
    }

    @GetMapping("/selectByLike")
    public Result selectByLike(@RequestParam String username, @RequestParam String name){
        List<User> users = userService.selectByLike(username,name);

        return Result.success(users);
    }

    @GetMapping("/selectByPage")
    public Result selectByPage(@RequestParam Integer pageNum,
                               @RequestParam Integer pageSize,
                               @RequestParam String username,
                               @RequestParam String name){
        Page<User> result = userService.selectByPage(pageNum, pageSize, username, name);

        return Result.success(result);
    }
}
